<?php
namespace app\api\controller\user;
use app\api\controller\Controller;
use app\api\model\Order as OrderModel;
use app\api\model\Wxapp as WxappModel;
use app\common\library\wechat\WxPay;
use app\api\model\User as UserModel;
use app\api\model\Goods as GoodsModel;
use app\api\model\Setting as SettingModel;
use app\api\model\Printer as PrinterModel;
use think\Cache;

/**
 * 用户订单管理
 */
class Order extends Controller
{
    private $user;

    /**
     * 构造方法
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->user = $this->getUser();   // 用户信息
    }

    /**
     * 我的订单列表
     */
    public function lists($dataType)
    {
        $model = new OrderModel;
        $list = $model->getList($this->user['user_id'], $dataType);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 订单详情信息
     */
    public function detail($order_id)
    {
        $order = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        return $this->renderSuccess(['order' => $order]);
    }

    /**
     * 取消订单
     */
    public function cancel($order_id)
    {
        $model = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        if ($model->cancel()) {
            return $this->renderSuccess();
        }
        return $this->renderError($model->getError());
    }

    /**
     * 确认收货
     */
    public function receipt($order_id)
    {
        $model = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        if ($model->receipt()) {
            return $this->renderSuccess();
        }
        return $this->renderError($model->getError());
    }

    /**
     * 立即支付
	 * $pay_mode 支付模式 0微信，1余额
     */
    public function pay($order_id,$pay_mode=0)
    {
        // 订单详情
        $order = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        // 判断商品状态、库存
        if (!$order->checkGoodsStatusFromOrder($order['goods'])) {
            return $this->renderError($order->getError());
        }
		if($pay_mode==0){
			// 发起微信支付
			$wxConfig = WxappModel::getWxappCache();
			$WxPay = new WxPay($wxConfig);
			$wxParams = $WxPay->unifiedorder($order['order_no'], $this->user['open_id'], $order['pay_price']);
			return $this->renderSuccess($wxParams);
		}
		//发起余额支付
		$user = UserModel::detail($this->user['user_id']);
		if($user['wallet']<$order['pay_price']){
			return [
				'code' => -10, 
				'msg' => '余额不足', 
				'data' => []
			];
		}
		$user->wallet = ['dec',$order['pay_price']];//扣除余额
		$user->pay = ['inc', $order['pay_price']];//增加消费金额
		//$user->score = ['inc', $order['pay_price']*100];//增加积分
		$user->save();
		//订单排序号
		if($row_no = Cache::get('order_row_no_'.$order['wxapp_id'].'_'.$order['shop_id'])){
			if($row_no<100){
				$row_no = $row_no+1;
			}else{
				$row_no=1;
			}	
		}else{
			$row_no = 1;
		}
		Cache::set('order_row_no_'.$order['wxapp_id'].'_'.$order['shop_id'], $row_no);		
		// 更新商品库存、销量
		$Goods = new GoodsModel;
		$Goods->updateStockSales($order['goods']);
		// 更新订单状态
		$order->row_no = $row_no;
		$order->pay_status = 20;
		$order->pay_time = time();
		$order->save();
		/*
		//发送模板消息 - 使用公众号
		if($this->user['union_id']){
			//判断是否关注公众号
			if($wxuser = UserModel::detail(['union_id' => $this->user['union_id'],'type' => 20])){
				//判断是否配置了模板消息
				$tmsg = SettingModel::getItem('tmsg',$wxuser['wxapp_id']);
				if($tmsg['payment']['template_id']){
					$tmsg['payment']['touser'] = $wxuser['open_id'];
					$tmsg['payment']['data']['keyword1']['value'] = $order['pay_price'].'元';
					$tmsg['payment']['data']['keyword2']['value'] = $order['order_no'];
					f_msg($tmsg['payment'],$wxuser['wxapp_id']); //发送模板消息
				}
			}	
		}
		*/	
		//获取打印机配置
		if($p_set = SettingModel::getItem('printer')){
			//如果开启打印机并且开启支付后打印 - 则执行打印小票
			if($p_set['is_open']==1 AND $p_set['pay_p']==1){
				$p = new PrinterModel;
				$p->gotoPrint($order,$p_set['p_n']);
			}
		}
		dealer($order['order_id']);
		return $this->renderSuccess(['order_id' => $order['order_id']]);
    }

}
